package com.itita.weibo.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import weibo4andriod.Count;
import weibo4andriod.Status;
import weibo4andriod.User;
import weibo4andriod.WeiboException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.itita.weibo.db.DataBaseOpenHelpler;
import com.itita.weibo.util.WeiboUtil;

public class WeiboDao {
   
	private Context context;
	
    private DataBaseOpenHelpler dataBaseOpenHelpler;
    
    public WeiboDao(Context context){
    	this.context = context;
    	dataBaseOpenHelpler = new DataBaseOpenHelpler(context);
    }
    
    public boolean clearCache(){
    	try {
			SQLiteDatabase  database =  this.dataBaseOpenHelpler.getReadableDatabase();
			database.execSQL("delete from home_table where 1 = 1");
			database.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	return false;
    }
    /**
     * 删除用户
     * @param username  用户账号
     */
    public void delUser(String username) throws Exception{
    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getReadableDatabase();
    	database.execSQL("delete from t_user where username=?", new Object[]{username});
    	database.close();
    }
    
    /**
     * 查询用户列表
     * @return
     */
    public ArrayList<User> searchUser(){
    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getReadableDatabase();
    	ArrayList<User> users = new ArrayList<User>();
    	StringBuffer sbSql = new StringBuffer();
    	sbSql.append("select * from t_user");
    	Cursor cursor = database.rawQuery(sbSql.toString(), null);
		 try{
			User user = null;
			while(cursor.moveToNext()){
				 user = new User();
				 user.setUsername(cursor.getString(1));
				 user.setLogin(cursor.getInt(2) == 1 ? true : false);
				 user.setPassword(cursor.getString(3));
				 user.setId(Integer.parseInt(cursor.getString(4)));
				 user.setName(cursor.getString(5));
				 
				 users.add(user);
			}
		  }finally{
			  
			if(cursor != null && !cursor.isClosed()){
				cursor.close();
			}
			database.close();
		  }
	   return users;
    }
	   
    /**
     * 根据用户账号查找用户
     * @param username
     * @return
     */
    public User findUser(String username){
    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getReadableDatabase();
    	String sql = "select * from t_user where username = '" + username +"'";
    	Cursor cursor = database.rawQuery(sql, null);
    	User user = null;
    	if(cursor.moveToNext()){
    		 user = new User();
			 user.setUsername(cursor.getString(1));
			 user.setLogin(cursor.getInt(2) == 1 ? true : false);
			 user.setPassword(cursor.getString(3));
			 user.setId(Integer.parseInt(cursor.getString(4)));
			 user.setName(cursor.getString(5));
			 
			 user.setAccessToken(cursor.getString(6));
			 user.setAccessTokenSecret(cursor.getColumnName(7));
			 
    	}
    	cursor.close();
    	database.close();
    	return user;
    }
     
    /**
     * 查找登陆用户
     * @return 登陆用户信息
     */
    public User findLoginingUser(){
    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getReadableDatabase();
    	String sql = "select * from t_user where islogin = 1";
    	Cursor cursor = database.rawQuery(sql, null);
    	User user = null;
    	if(cursor.moveToNext()){
    		 user = new User();
			 user.setUsername(cursor.getString(1));
			 user.setLogin(cursor.getInt(2) == 1 ? true : false);
			 user.setPassword(cursor.getString(3));
			 user.setId(Integer.parseInt(cursor.getString(4)));
			 user.setName(cursor.getString(5));
			 
			 user.setAccessToken(cursor.getString(6));
			 user.setAccessTokenSecret(cursor.getString(7));
			 
    	}
    	cursor.close();
    	database.close();
    	return user;
    }
    /**
     * 更新登陆用户信息
     * @param user
     */
	 public void updateUser(User user){
	    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getWritableDatabase();
	    	StringBuffer sbSql = new StringBuffer();
	    	sbSql.append("update t_user set  password=?,islogin=? where username=? ");
	    	database.execSQL(sbSql.toString(), new Object[]{user.getPassword(), user.isLogin()? 1 : 0, user.getUsername()});  
	    	database.close();
     }
	 
   /**
    * 添加用户
    * 
    * @param username 用户名
    * @param password  密码由于采用(OAuth认证 所以不是必须持久化)
    * @param isLogin 使用是登陆用户
    * @param userId 用户ID
    * @param name 用户名称
    * @param accessToken 访问令牌
    * @param accessTokenSecret 访问令牌密钥
    */
    public void addUser(String username, String password, boolean isLogin, int userId, String name, String accessToken, String accessTokenSecret){
    	
    	ContentValues values = new ContentValues();
    	if(this.findUser(username) != null){ //差看用户是否已经存在
    		User user = new User();
    		user.setUsername(username);
    		user.setPassword(password);
    		user.setLogin(isLogin);
    		this.updateUser(user);
    	}else{
    		values.put("username", username);
        	values.put("password", password);
        	values.put("islogin", isLogin ? 1 : 0);
        	values.put("userid", String.valueOf(userId));
        	values.put("name", name);
        	values.put("accessToken", accessToken);
        	values.put("accessTokenSecret", accessTokenSecret);
        	
        	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getWritableDatabase();
        	database.insert("t_user", null, values);
        	database.close();
        	
        	if(isLogin){ //将其他用户该为不可登陆的状态
        	    ArrayList<User> users = this.searchUser();
        	    for (Iterator iterator = users.iterator(); iterator.hasNext();) {
    				User user = (User) iterator.next();
    				if(!user.getUsername().equals(username)){
    					user.setLogin(false);
    					
    					this.updateUser(user);
    				}
    			}
        	}
    	}
    }
    /**
     * 添加主页信息
     * @param status 
     * @param userId 当前要保存的登陆信息是属于哪个用等用户
     */
    public void addHomeTableData(Status status, int userId){
    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getWritableDatabase();
    	ContentValues values = new ContentValues();
        User user = status.getUser();
        
    	values.put("statusid", String.valueOf(status.getId()));
    	values.put("uid", String.valueOf(user.getId()));
    	values.put("nick", String.valueOf(user.getName()));
    	values.put("portrait", String.valueOf(user.getProfileImageUrl()));
    	values.put("vip", String.valueOf(user.isVerified() ? 1 : 0));
    	values.put("content", String.valueOf(status.getText()));
    	values.put("pic", String.valueOf(status.getBmiddle_pic()));
    	values.put("time", String.valueOf(status.getCreatedAt().getTime()));
    	Status retweetedStatus = status.getRetweetedStatus();
    	if(retweetedStatus != null){
    		User retweetedUser = retweetedStatus.getUser();
    		values.put("rtstatusid", String.valueOf(retweetedStatus.getId()));
    		values.put("rtrootuid", String.valueOf(retweetedUser.getId()));
    		values.put("rtrootnick", String.valueOf(retweetedUser.getName()));
    		values.put("rtrootvip", String.valueOf(retweetedUser.isVerified() ? 1 : 0));
    		values.put("rtreason", retweetedStatus.getText());
    	}
    	long rtnum = 0;
    	long commentnum = 0;
    	try {
    		HashMap<String, Long> countInfo = this.getStatusCountInfoByStatusId(status.getId());
    		rtnum = countInfo.get(WeiboUtil.RT_NUM);
    		commentnum = countInfo.get(WeiboUtil.COMMENT_NUM);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
    	values.put("rtnum",rtnum);
    	values.put("commentnum", commentnum);
    	values.put("src",  WeiboUtil.getComeFromSource(status.getSource()));
    	values.put("longitude", String.valueOf(status.getLongitude()));
    	values.put("latitude", String.valueOf(status.getLatitude()));
    	
    	//权值 ----->用户的推荐权值
    	values.put("weight", String.valueOf(WeiboUtil.getUserRecommendWeight(user.getFollowersCount(), user.getFriendsCount(), user.getStatusesCount())));
    	
//    	values.put("weight", String.valueOf(WeiboUtil.calStatusWeight(rtnum, commentnum)));

    	values.put("userid", String.valueOf(userId));
    	
    	values.put("fansNum", String.valueOf(user.getFollowersCount()));
    	values.put("attentionNum", String.valueOf(user.getFriendsCount()));
    	values.put("statusNum", String.valueOf(user.getStatusesCount()));
    	
    	
    	database.insert("home_table", null, values);
    	
      database.close();
    	
    }
    
    /**
     * 从本地查询所有的微博信息 
     * @param orderByName
     * @param userId
     * @return
     */
    public ArrayList<Status> searchStatuesFromLocal(String orderByName, int userId){
    	SQLiteDatabase  database =  this.dataBaseOpenHelpler.getReadableDatabase();
    	ArrayList<Status> statuses = null;
    	try { 
			statuses = locadStatuesFromLocal(database, orderByName, userId);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			database.close();
		}
		return statuses;
    }
    /**
	 * 从本地加载信息
	 * @param database
	 * @param orbyName
	 * @param userId
	 * @return
	 * @throws Exception where id=30 
	 */
    private static final ArrayList<Status> locadStatuesFromLocal(SQLiteDatabase database, String orbyName, int userId) throws Exception{
    	ArrayList<Status> statuses = new ArrayList<Status>();
    	StringBuffer sbSql = new StringBuffer();
    	sbSql.append("select * from home_table ")
    	     .append("where userid=? ")
    	     .append(" group by statusid ") //---->分组去掉重复的内容
    	     .append(" order by ")
    	     .append(orbyName);
		////System.out.println("SQL语句：" + sbSql.toString());
    	Cursor cursor = database.rawQuery(sbSql.toString(), new String[]{String.valueOf(userId)});
		 try{
			Status status = null;
			User user = null;
			Status rtStatus = null;
			User rtUser = null;
			while(cursor.moveToNext()){
				 status = new Status();
				 user = new User();
				 status.setId(Long.parseLong(cursor.getString(1)));
				 
				 user.setId(Integer.parseInt(cursor.getString(2)));
				 user.setName(cursor.getString(3));
				 user.setProfileImageUrl(cursor.getString(4));
				 user.setVerified(cursor.getInt(5) == 1 ? true : false);
				 
				 
			 
				 try {
					user.setFollowersCount(cursor.getString(21) != null ? Integer.parseInt(cursor.getString(21)) : 0);//粉丝数
					user.setFriendsCount(cursor.getString(22) != null  ? Integer.parseInt(cursor.getString(22)) : 0); //关注数
					user.setStatusesCount(cursor.getString(23) != null ? Integer.parseInt(cursor.getString(23)) : 0);  //用户所发表的微博数
			
				 } catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				 status.setUser(user);
				 
				 status.setText(cursor.getString(6));
				 status.setBmiddle_pic(cursor.getString(7));
				 status.setCreatedAt(new Date(Long.parseLong(cursor.getString(8))));
//				 ////System.out.println("cursor.getString(9):" + cursor.getString(9));
				 long rtStatusId = Long.parseLong(cursor.getString(9) != null ? cursor.getString(9) : "0");
				 if(rtStatusId != 0){
					 rtUser = new User();
					 rtStatus  = new Status();
					 rtStatus.setId(rtStatusId);
					 rtUser.setId(Integer.parseInt(cursor.getString(10)));
					 rtUser.setName(cursor.getString(11));
					 rtUser.setVerified(cursor.getInt(12) == 1 ? true : false);
					
					 rtStatus.setUser(rtUser);
					 rtStatus.setText(cursor.getString(13));
					 
					 status.setRetweetedStatus(rtStatus);
				 }
				 //设置转发数
				 status.setRetweetedNum(cursor.getInt(14));
				 //设置评论数
				 status.setCommNum(cursor.getInt(15));
				 status.setSource(cursor.getString(16));
				 
				 status.setLongitude(Double.parseDouble(cursor.getString(17)));
				 status.setLatitude(Double.parseDouble(cursor.getString(18)));
//				ddd
				 status.setWeight(Float.parseFloat(cursor.getString(19))); 
				 statuses.add(status);
			     Log.i("INFO", "---------------从本地加载一条数据数据完毕---------------");
			}
		  }finally{
			if(cursor != null && !cursor.isClosed()){
				cursor.close();
			}
		  }
	   return statuses;
    }
    
    /**
	 * 获取某条微博的统计信息(评论，转发的统计信息)
	 * @param statusId 
	 * @return 某条微博的统计信息(评论，转发的统计信息)
	 * @throws WeiboException 
	 */
	public static final HashMap<String, Long> getStatusCountInfoByStatusId(long statusId) throws WeiboException{
		List<Count> counts = MainService.mainService.weibo.getCounts(String.valueOf(statusId));
		HashMap<String, Long> countInfo = new HashMap<String, Long>();
		countInfo.put(WeiboUtil.COMMENT_NUM,  counts.get(0).getComments());
		countInfo.put(WeiboUtil.RT_NUM,       counts.get(0).getRt());
//		for (Count count:counts){
//		    ////System.out.println("统计信息:"+count.getComments()+" - "+ count.getRt());
//		}
		return countInfo;
	} 
}
